/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.logging;

import org.slf4j.bridge.SLF4JBridgeHandler;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * Abstract base class for {@link LoggingSystem} implementations that utilize SLF4J.
 *
 * @author Andy Wilkinson
 * @since 1.2.0
 */
public abstract class Slf4JLoggingSystem extends AbstractLoggingSystem {

	private static final String BRIDGE_HANDLER = "org.slf4j.bridge.SLF4JBridgeHandler";

	public Slf4JLoggingSystem(ClassLoader classLoader) {
		super(classLoader);
	}

	@Override
	public void beforeInitialize() {
		// 调用父类的beforeInitialize，默认父类实现为空
		super.beforeInitialize();
		// 配置jdk内置日志与slf4j直接的桥接handler
		configureJdkLoggingBridgeHandler();
	}

	@Override
	public void cleanUp() {
		removeJdkLoggingBridgeHandler();
	}

	@Override
	protected void loadConfiguration(LoggingInitializationContext initializationContext, String location, LogFile logFile) {
		Assert.notNull(location, "Location must not be null");
		if (initializationContext != null) {
			applySystemProperties(initializationContext.getEnvironment(), logFile);
		}
	}

	/**处理内置日志（JUL）与slf4j的handler的桥接转换操作
	 * <br/>基本逻辑如下：如果类路径下存在SLF4JBridgeHandler类，并且根Logger中不包含或仅包含ConsoleHandler时，说明需要将内置日志转换为slf4j
	 * <br/>基本转换过程走两步：删除原有handler、新增指定的handler；如果满足条件，先删除内置日志的handler，然后再删除slf4j的handler，最后再将slf4j对应的SLF4JBridgeHandler添加到根Logger中
	 */
	private void configureJdkLoggingBridgeHandler() {
		try {
			// 判断是否需要将JUL桥接为slf4j
			if (isBridgeHandlerAvailable()) {
				// 删除jdk内置日志的handler
				removeJdkLoggingBridgeHandler();
				// 添加slf4j的handler
				SLF4JBridgeHandler.install();
			}
		}
		catch (Throwable ex) {
			// Ignore. No java.util.logging bridge is installed.
		}
	}

	protected final boolean isBridgeHandlerAvailable() {
		// 判断org.slf4j.bridge.SLF4JBridgeHandler是否存在于类路径下
		return ClassUtils.isPresent(BRIDGE_HANDLER, getClassLoader());
	}

	private void removeJdkLoggingBridgeHandler() {
		try {
			if (isBridgeHandlerAvailable()) {
				try {
					SLF4JBridgeHandler.removeHandlersForRootLogger();
				}
				catch (NoSuchMethodError ex) {
					// Method missing in older versions of SLF4J like in JBoss AS 7.1
					SLF4JBridgeHandler.uninstall();
				}
			}
		}
		catch (Throwable ex) {
			// Ignore and continue
		}
	}

}
